﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Moonlite.Platform.Ximl {
    public static class ResourceManager {
        public static Stream GetStream(string resourcePath, Type type) {
            return GetStream(resourcePath, type.Assembly);
        }
        public static Stream GetStream(string resourcePath, Assembly assembly) {
            Stream stream = assembly.GetManifestResourceStream(resourcePath);
            if (stream == null) {
                throw new ResourceNotFoundException("Resource not found: " + resourcePath);
            }
            return stream;
        }
        public static string GetStringFromResourceString(string resourceString) {
            if (XimlTree.Instance.CurrentAssembly == null) {
                throw new NoAssemblyContextException("No valid assembly context found.");
            }
            foreach (string key in XimlTree.Instance.Resources.Keys) {
                if (key == resourceString && XimlTree.Instance.Resources[key].GetType() == ResourceTypes.StringType) {
                    return (string)XimlTree.Instance.Resources[key];
                }
            }
            return "";
        }
        public static bool ResourceExists(string resourceString, Type type) {
            if (XimlTree.Instance.CurrentAssembly == null) {
                throw new NoAssemblyContextException("No valid assembly context found.");
            }
            foreach (string key in XimlTree.Instance.Resources.Keys) {
                if (key == resourceString && XimlTree.Instance.Resources[key].GetType() == type) {
                    return true;
                }
            }
            return false;
        }
        public static string ConvertReferenceToString(string reference) {
            if (reference.StartsWith("$")) {
                reference = reference.TrimStart('$');
                if (!ResourceManager.ResourceExists(reference, ResourceTypes.StringType)) {
                    throw new InvalidOperationException("");
                }
                else {
                    reference = ResourceManager.GetStringFromResourceString(reference);
                }
            }
            return reference;
        }
    }
}
